package com.chuanyang.driverh.mainstart;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.chuanyang.driverh.R;
import com.chuanyang.driverh.base.BaseActivity;
import com.chuanyang.driverh.responseresult.RegistResult;
import com.chuanyang.driverh.responseresult.ValidateCodeResult;
import com.chuanyang.driverh.utils.ConstUtil;
import com.chuanyang.driverh.utils.DialogUtil;
import com.chuanyang.driverh.utils.NetUtil;
import com.chuanyang.driverh.utils.PrintUtil;
import com.chuanyang.driverh.utils.SharedPrefUtil;
import com.chuanyang.driverh.utils.StringUtil;
import com.chuanyang.driverh.utils.net.JsonGenericsSerializator;
import com.chuanyang.driverh.utils.net.MyCallback;
import com.chuanyang.driverh.utils.net.MyHttpUtil;

import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;

public class RegisterOrForgetPwdActivity extends BaseActivity {
    private EditText et_register_account;//注册账户
    private EditText et_register_password;//密码
    private EditText et_register_password2;//重复密码
    private EditText et_get_code;//验证码输入框
    private Button bt_code;//获取验证码
    private Button btn_register;//注册
    private ImageView iv_back;
    private TextView tv_reg_foget;

    private MyCountDownTimer countDown;
    private int type;//1注册，2忘记密码

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.start_act_register);
        initView();
        initData();
        initListener();
    }

    private void initView() {
        et_register_account = (EditText) findViewById(R.id.et_register_account);//注册账户
        et_register_password = (EditText) findViewById(R.id.et_register_password);//密码
        et_register_password2 = (EditText) findViewById(R.id.et_register_password2);//重复密码
        et_get_code = (EditText) findViewById(R.id.et_get_code);//验证码输入框
        bt_code = (Button) findViewById(R.id.bt_code);//获取验证码
        btn_register = (Button) findViewById(R.id.btn_register);//注册

        tv_reg_foget = (TextView) findViewById(R.id.tv_reg_foget);
        iv_back = (ImageView) findViewById(R.id.iv_regist_back);


    }

    private void initData() {
        type=getIntent().getIntExtra("type",1);
        tv_reg_foget.setText(type==1?"注册":"忘记密码");
        bt_code.setBackgroundResource(R.drawable.bt_shape_round_corner_getcode);
    }

    private void initListener() {
        btn_register.setOnClickListener(this);
        bt_code.setOnClickListener(this);
        iv_back.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_register:
                checkAll();
                break;
            case R.id.iv_regist_back:
                onBackPressed();
                break;
            case R.id.bt_code:
               String phone=et_register_account.getText().toString().trim();
                if(StringUtil.isPhoneNumber(phone)){
                    getCode(phone);
                }else{
                    PrintUtil.toast(activityContext,"请输入正确的手机号");
                }
                break;
        }
    }

    private void getCode( String phone) {
        if (!NetUtil.checkNetworkIfAvailable(activityContext)) {
            PrintUtil.toast(activityContext, "请检查网络");
            return;
        }

        DialogUtil.showLoadingDialog(activityContext,"验证码...");
        Map<String,String> params=new HashMap<String, String>();
        params.put("phone", phone);

        MyHttpUtil.getCode(activityContext,params, new MyCallback<ValidateCodeResult>(activityContext,new JsonGenericsSerializator()) {
            @Override
            public void onFail(Call call, Exception e, int id) {
                e.printStackTrace();
                PrintUtil.toast(activityContext, "网络异常，请稍后再试");
            }

            @Override
            public void onSuccess(ValidateCodeResult result, int id) {
                if (result.getCode() == ConstUtil.OK) {
                    startCountdown();
                }else{
                    PrintUtil.toast(activityContext,result.getMsg());
                }
            }
        });



    }
    /**
     * 检查
     */
    private void checkAll() {
        String phone=et_register_account.getText().toString().trim();
        String pwd1=et_register_password.getText().toString().trim();
        String pwd2=et_register_password2.getText().toString().trim();
        String code=et_get_code.getText().toString().trim();

        if (!StringUtil.isPhoneNumber(phone)) {
          PrintUtil.toast(activityContext, "请输入11位手机号");
            return ;
        }
        if (pwd1.length() < 6 || pwd1.length() > 20) {
            PrintUtil.toast(activityContext, "请输入6-20位的密码");
            return;
        }
        if (StringUtil.isBlank(pwd2)|| !pwd1.equals(pwd2)) {
            PrintUtil.toast(activityContext, "请确认两次输入的密码一致");
            return;
        }
        if (StringUtil.isBlank(code)) {
           PrintUtil.toast(activityContext, "请输入验证码");
            return;
        }

        registerOrChangePwd(phone,pwd1,code);
    }

    private void registerOrChangePwd(final String phone,final String pwd,String code) {
        DialogUtil.showLoadingDialog(activityContext,type==1?"注册...":"修改密码");
        Map<String,String> params=new HashMap<String, String>();
        params.put("phone",phone);
        params.put("password",pwd);
        params.put("userType", "2");
        params.put("validateCode", code);
        MyHttpUtil.registerOrChangePwd(activityContext,type,params, new MyCallback<RegistResult>(activityContext,new JsonGenericsSerializator()) {
            @Override
            public void onFail(Call call, Exception e, int id) {
                e.printStackTrace();
                PrintUtil.toast(activityContext, "网络异常，请稍后再试");
            }

            @Override
            public void onSuccess(RegistResult result, int id) {
                if (result.getCode() == ConstUtil.OK) {
                    SharedPrefUtil.setPhone(phone);
                    SharedPrefUtil.setPwd(pwd);
                    PrintUtil.toast(activityContext,type==1?"您已注册成功":"密码修改成功");
                    onBackPressed();
                }else{
                    PrintUtil.toast(activityContext,result.getMsg());
                }
            }
        });

    }


    private void startCountdown() {
        countDown = new MyCountDownTimer(90000, 1000);
        countDown.start();
    }

    @Override
    public void finish() {
        super.finish();
        if (countDown != null) countDown.cancel();
    }
    class MyCountDownTimer extends CountDownTimer {
        public MyCountDownTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);

        }

        @Override
        public void onFinish() {
            super.cancel();
            bt_code.setText("获取验证码");
            bt_code.setBackgroundResource(R.drawable.bt_shape_round_corner_getcode);
            bt_code.setEnabled(true);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            bt_code.setText("重新获取" +(millisUntilFinished / 1000) + "s");
            bt_code.setEnabled(false);
            bt_code.setBackgroundResource(R.drawable.round_corner_whitegray_shape);
        }
    }

}
